#### Code to replicate Figure A2 in the Appendix of "Nonpartisan Ballots and the Partisanship of Who Serves in Office"

df.vf.26_2 <- read.csv("officials-2017_voterfile-merged_public.csv")

head(df.vf.26_2)

# Define the colors for the graph
# Make base colors transparent
overlay_colors <- c("darkcyan", "darkgoldenrod3", "tomato2")
alpha <- 0.4
tcols <- apply(col2rgb(overlay_colors),2,function(x) rgb(x[1]/255, x[2]/255, x[3]/255, alpha=alpha))
base_color <- "darkorchid4"

# Create function to mix colors so we can use the final colors in the legend of the plot
mix_colors <- function(color1, alpha1, color2, alpha2) {
  # Convert colors to RGBA
  rgba1 <- grDevices::col2rgb(color1, alpha = TRUE) / 255
  rgba2 <- grDevices::col2rgb(color2, alpha = TRUE) / 255
  
  # Apply the alpha values
  rgba1[4] <- alpha1
  rgba2[4] <- alpha2
  
  # Calculate the mixed color
  mixed_rgb <- (rgba1[1:3] * rgba1[4] + rgba2[1:3] * rgba2[4]) / (rgba1[4] + rgba2[4])
  mixed_alpha <- 1 - (1 - rgba1[4]) * (1 - rgba2[4])
  
  # Return the resulting color
  grDevices::rgb(mixed_rgb[1], mixed_rgb[2], mixed_rgb[3], mixed_alpha)
}

# Mix each overlay with the base color
mixed_colors <- sapply(overlay_colors, mix_colors, alpha1 = alpha, color2 = base_color, alpha2 = 1)

# Create plot with transparent color panels indicating the classification tag according to the level of quality
pdf("qualityscores.pdf")
hist(df.vf.26_2$L2_qualityindex, main="", col="darkorchid4", xaxt="n", yaxt="n", xlab="", ylab="")
polygon(c(0,0.2, 0.2,0), c(-5,-5,85000,85000), col=tcols[1], border=NA)
polygon(c(0.2,0.4, 0.4,0.2), c(-5,-5,85000,85000), col=tcols[2], border=NA)
polygon(c(0.4,2, 2,0.4), c(-5,-5,85000,85000), col=tcols[3], border=NA)
axis(1, cex.axis=0.9, cex.lab=0.9, mgp=c(0.3, 0.3, 0), lwd=0, lwd.ticks = 1, tck=0.02)
axis(2, at=seq(0,80000,20000), labels= seq(0,80000,20000)/1000, tck=0.01, cex.axis=0.9, cex.lab=0.9, mgp=c(0.3, 0.3, 0), lwd=0, lwd.ticks = 1)
abline(v=c(0.2, 0.4), col="darkred", lty=2)
title(xlab = "Quality score", line = 1.5, cex.lab = 1, ylab="")
title(xlab = "", line = 1.5, cex.lab = 1, ylab="Frequency (in thousands)")
title(xlab = "", ylab="", main = "Distribution of quality scores", font.main=1)
box("plot")
legend(1.5,70000, legend = c("High", "Medium", "Low"), fill = mixed_colors, bty="n", cex=0.8)
dev.off()

